package com.xxx.video.commen.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class UriUtils {
    private static UriUtils mUriUtils = null;

    private UriUtils() {
    }

    public static UriUtils getInstance() {
        if (mUriUtils == null) {
            synchronized (UriUtils.class) {
                if (mUriUtils == null) {
                    mUriUtils = new UriUtils();
                }
            }
        }
        return mUriUtils;
    }

    /**
     * @param activity   activity
     * @param contentUri uri
     * @return file path
     */
    public String getRealPathFromURI(Activity activity, Uri contentUri) {
        String result = "";
        Cursor cursor = activity.getContentResolver().query(contentUri, null, null, null, null);
        if (cursor == null) {
            result = contentUri.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

    /**
     * @param activity   activity
     * @param contentUri uri
     * @return file path
     */
    public String getVideoRealPathFromURI(Activity activity, Uri contentUri) {
        String result = "";
        Cursor cursor = activity.getContentResolver().query(contentUri, null, null, null, null, null);
        if (cursor == null) {
            result = contentUri.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Video.VideoColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

    /**
     * @param activity   activity
     * @param contentUri uri
     * @return file path
     */
    public long getVideoDurationFromURI(Activity activity, Uri contentUri) {
        long result = 0L;
        Cursor cursor = activity.getContentResolver().query(contentUri, null, null, null, null, null);
        if (cursor == null) {
            result = 0;
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
            result = cursor.getLong(idx);
            cursor.close();
        }
        return result;
    }
}
